package plus.xj17520.org.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import plus.xj17520.base.constants.Constants;
import plus.xj17520.org.service.IFileService;
import plus.xj17520.base.utils.FileOV;
import plus.xj17520.base.result.JSONResult;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @projectName: pethomeProject
 * @package: plus.xj17520.org.service.impl
 * @className: FileServiceImpl
 * @author: XiaoJue
 * @description: TODO
 * @date: 2022/5/25 11:06
 * @version: 1.0
 */
@Service
public class FileServiceImpl implements IFileService {

    @Override
    public JSONResult fileUpload(MultipartFile file) {

    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    String endpoint = Constants.ENDPOINT;
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    String accessKeyId = Constants.ACCESSKEYID;
    String accessKeySecret = Constants.ACCESSKEYSECRET;
    // 填写Bucket名称，例如examplebucket。
    String bucketName = Constants.BUCKET;

    //获取上传文件后缀+得到最后.的后缀名+获取后缀
    String originalFilename = file.getOriginalFilename();
    int i = originalFilename.lastIndexOf(".");
    String fileType = originalFilename.substring(i);

    //填写Object完整路径，完整路径中不能包含Bucket名称
    String fileName = UUID.randomUUID().toString().replace("-", "") + fileType;

    // 创建OSSClient实例。
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    try {
        InputStream inputStream = file.getInputStream();
        // 创建PutObject请求
        ossClient.putObject(bucketName, fileName, inputStream);

    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message:" + oe.getErrorMessage());
        System.out.println("Error Code:" + oe.getErrorCode());
        System.out.println("Request ID:" + oe.getRequestId());
        System.out.println("Host ID:" + oe.getHostId());
    } catch (ClientException ce) {
        System.out.println("上传文件OSS异常：" + ce.getMessage());
        return JSONResult.error(ce.getMessage());
    }catch (IOException ie){
        System.out.println("上传文件流异常：" + ie.getMessage());
        return JSONResult.error(ie.getMessage());
    } finally {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
    //拼接URL地址返回给前端
    //https://blog0217.oss-cn-chengdu.aliyuncs.com/77786f3d6f31445bad462e5464085de8.jpg
    String url="https://"+bucketName+"."+endpoint+"/"+fileName;
    return JSONResult.success(url);
}

    @Override
    public JSONResult fileDel(FileOV fileOV) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = Constants.ENDPOINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = Constants.ACCESSKEYID;
        String accessKeySecret = Constants.ACCESSKEYSECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = Constants.BUCKET;

        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        String url = fileOV.getUrl();

        int i = (url.lastIndexOf("/")+1);

        String substring = url.substring(i);

        System.out.println(substring);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, substring);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return JSONResult.success();
    }
}
